package com.dong.mcd.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dong.mcd.dao.SysUserMapper;
import com.dong.mcd.model.SysRole;
import com.dong.mcd.model.SysUser;
import com.dong.mcd.model.SysUserExample;
import com.dong.mcd.model.SysUserExample.Criteria;
import com.dong.mcd.param.UserParam;
import com.dong.mcd.service.IUserService;
import com.dong.mcd.util.CollectionUtil;
import com.dong.mcd.util.MD5Util;
import com.dong.mcd.util.PageConfig;

@Transactional
@Service("userService")
public class UserServiceImpl implements IUserService {

	@Autowired
	private SysUserMapper userMapper;
	
	public void add(SysUser user) {
		userMapper.insert(user);
		System.out.println("刚刚插入的id:"+user.getId());
	}

	public SysUser get(Integer id) {
		return userMapper.selectByPrimaryKey(id);
	}

	public SysUser login(String loginName, String password) {
		String enPwd = MD5Util.md5Digest(password);
		SysUserExample example = new SysUserExample();
		example.createCriteria()
					.andLoginNameEqualTo(loginName)
					.andPasswordEqualTo(enPwd)
					.andStatusEqualTo(1);
		List<SysUser> list = userMapper.selectByExample(example);
		if (CollectionUtil.isEmpty(list))
				return null;
		return list.get(0);
	}

	public void modify(SysUser user) {
		userMapper.updateByPrimaryKeySelective(user);
	}

	public List<SysUser> query(UserParam param) {
		SysUserExample example = new SysUserExample();
		Criteria criteria = example.createCriteria();
		if (StringUtils.isNotEmpty(param.getLoginName()))
			criteria.andLoginNameEqualTo(param.getLoginName());
		if (StringUtils.isNotEmpty(param.getUserName()))
				criteria.andUserNameEqualTo(param.getUserName());
		if (param.getStatus() != null)
			criteria.andStatusEqualTo(param.getStatus());
		return userMapper.selectByExample(example);
	}

	public PageConfig queryPage(UserParam param, Integer pageIndex,
			Integer pageSize) {
		SysUserExample example = new SysUserExample();
		Criteria criteria = example.createCriteria();
		if (StringUtils.isNotEmpty(param.getLoginName()))
			criteria.andLoginNameLike("%"+param.getLoginName()+"%");
		if (StringUtils.isNotEmpty(param.getUserName()))
			criteria.andUserNameLike("%"+param.getUserName()+"%");
		if (param.getStatus() != null)
			criteria.andStatusEqualTo(param.getStatus());
		return new PageConfig(userMapper,example,pageIndex,pageSize);
	}
	public void remove(Integer id) {
		userMapper.deleteByPrimaryKey(id);
	}

	public void saveUserRole(UserParam param) {
		userMapper.deleteUserRole(param);
		userMapper.saveUserRole(param);
	}

	public List<SysRole> getUserRoles(Integer userId) {
		return userMapper.getUserRoles(userId);
	}

	
}
